package com.cjd.common.utils

import android.content.Context
import android.media.AudioAttributes
import android.media.AudioManager
import android.media.SoundPool
import android.os.Build

/**
 * @Author chenjidong
 * @email 374122600@qq.com
 * created 2020-04-05
 * description 铃声工具包
 */
object RingtoneUtil {

    private val soundPool: SoundPool by lazy {
        return@lazy if (Build.VERSION.SDK_INT >= 21) {
            SoundPool.Builder()
                .setMaxStreams(1)
                .setAudioAttributes(AudioAttributes.Builder().setLegacyStreamType(AudioManager.STREAM_MUSIC).build())
                .build()
        } else
            SoundPool(1, AudioManager.STREAM_MUSIC, 0)
    }

    /**
     * @param context 上下文
     * @param rawResId raw 资源
     * @param priority 声音优先级
     * @return 加载后的 资源ID 用于播放
     */
    fun load(context: Context, rawResId: Int, priority: Int = 1): Int {
        return try {
            soundPool.load(context, rawResId, priority)
        } catch (e: Exception) {
            -1
        }
    }

    /**
     * 播放铃声
     * @param context 上下文
     * @param sound 加载后的资源ID
     * @param loop 循环次数
     * @return 0失败
     */
    fun playerSound(context: Context, sound: Int, loop: Int = 0): Int {
        if (sound == -1)
            return 0
        val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager?
        audioManager?.let {
            val currentVolume = it.getStreamVolume(AudioManager.STREAM_MUSIC)
            val maxVolume = it.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
            val volume = currentVolume * 1f / maxVolume

            /**
             * 1.soundID load方法返回的值,指向某个已加载的音频资源
             * 2.leftVolume\rightVolume 用来这种左右声道的值.范围 0.0f ~ 1.0f
             * 3.priority 流的优先级
             * 4.loop 循环播放的次数, -1 表示无限循环
             * 5.rate 播放的速率 , 2 表示2倍速度
             */
            return soundPool.play(sound, volume, volume, 1, loop, 1f)
        }
        return 0
    }
}